package com.judian.smart.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.judian.smart.util.ToastPlus;
import com.judian.smart.util.WeatherTimeTask;


public class NetworkReceiver extends BroadcastReceiver {
    private static final String TAG = NetworkReceiver.class.getCanonicalName();
    public static final int NET_ETHERNET = 1;
    public static final int NET_WIFI = 2;
    public static final int NET_NO = 0;

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "生命周期 onReceive: !!!!!!!!!!!");
        switch (isNetworkAvailable(context)) {
            case NET_ETHERNET:
                Log.d(TAG, "onReceive: 以太网连接成功");
                WeatherTimeTask.getInstance().restart();
                break;
            case NET_WIFI:
                Log.d(TAG, "onReceive: WIFI连接成功！");
                WeatherTimeTask.getInstance().restart();
                break;
            case NET_NO:
                ToastPlus.showError("网络已断开");
                Log.d(TAG, "onReceive: 网络断开！");
                break;
            default:
                break;
        }
    }

    private int isNetworkAvailable(Context context) {
        ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ethNetInfo = connectManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
        NetworkInfo wifiNetInfo = connectManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (ethNetInfo != null && ethNetInfo.isConnected()) {
            return NET_ETHERNET; //以太网
        } else if (wifiNetInfo != null && wifiNetInfo.isConnected()) {
            return NET_WIFI;    //WIFI
        } else {
            return NET_NO;  //没网络
        }
    }
}
